'use strict';


const Controller = require('egg').Controller;

// 定义创建接口的请求参数规则
const createRule = {
  categoryId: 'number',
  title: 'string',
  cover: {
    type: 'string',
    required: true,
  },
  abstract: 'string',
  content: 'string',
  keywords: 'string',
  tags: 'string',
  source: 'string',
  status: 'number',
};

const updateRule = {
  categoryId: 'number',
  title: 'string',
  cover: {
    type: 'string',
    required: false,
  },
  abstract: 'string',
  content: 'string',
  keywords: 'string',
  tags: 'string',
  source: 'string',
  status: 'number',
};

class ArticleController extends Controller {
  async index() {
    const ctx = this.ctx;
    const { cms: { article } } = ctx.service;
    const data = await article.find(ctx.query);
    ctx.success({ data });
  }

  async show() {
    const ctx = this.ctx;
    const { cms: { article } } = ctx.service;
    const data = await article.findOne(ctx.params);
    ctx.success({ data });
  }

  async create() {
    const ctx = this.ctx;
    const { cms: { article } } = ctx.service;
    ctx.validate(createRule);
    try {
      const id = await article.create(ctx.request.body);
      const data = {
        id,
      };
      ctx.success({ data });
    } catch (error) {
      ctx.error({ detail: error });
    }
  }

  async update() {
    const ctx = this.ctx;
    const { cms: { article } } = ctx.service;
    ctx.validate(updateRule);
    try {
      const params = Object.assign({ id: ctx.params.id }, ctx.request.body);
      const data = await article.update(params);
      ctx.success({ data });
    } catch (error) {
      ctx.error({ detail: error });
    }
  }

  async destroy() {
    const ctx = this.ctx;
    const { cms: { article } } = ctx.service;
    const data = await article.destroy(ctx.params);
    ctx.success({ data });
  }
}

module.exports = ArticleController;
